﻿<script language="javascript" type="text/javascript" src="./js/jquery.showhide.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="./js/jquery.autoresize.js"></script>

<?php
$database->cyr_chars();

//----------------------------------------------------------
//----------- CHANGEABLE PART ------------------------------
//----------------------------------------------------------

//---> LOADING DYNAMIC INFO
$CMS_game = $_GET['game'];
$page_class = "PlayON";	 //Key for non-users
$CMS_fieldheight = "150px";

//---> ESTABLISHING USER ARRAYS AS STRINGS
		$admins = "Mnementh||xakepa||3pacalypse Now||benzinjiq||purpleisdead||HeBuguM||moonface||aXe||Zlo||e-VIL||mitaka18||tsetse||moga";
		$moderators= "||Mnementh||LawFall||xakepa||3pacalypse Now||benzinjiq||purpleisdead||HeBuguM||moonface||aXe||Zlo||mitaka18||e-VIL||tsetse||moga||";
		$adminss=        array("xakepa","3pacalypse Now","benzinjiq","purpleisdead","HeBuguM","moonface","aXe","Zlo","e-VIL","mitaka18","Mnementh","tsetse","moga");
		$mods=          array("LawFall","xakepa","3pacalypse Now","benzinjiq","purpleisdead","HeBuguM","moonface","aXe","Zlo","mitaka18","e-VIL","Mnementh","tsetse","moga");
		$hidden_games=  array("GTA4","Uncharted","SecretFiles2","RE5","MoveHeroes","CW","MAL");
		$game_prefixes= array("aom","batman","bid","castlevania","conan","civ5","diablo2","disc3","gothic","grimtales","gta4","hpotter3","moveheroes","oblivion","re5","rome","saw","secretspast","secretfiles2","sh4","shawakened","shvsjtr","unc3","wwp","cw","mal");
		
//---> CHECK PRIVILEGES
function privilege_chk($user_approve, $user_add = "registered", $user_see = "all", $user_name)
{
	$user_status = array("APPROVE" => 0, "ADD" => 0, "SEE" => 1);
	$a["app"]= explode ("||",  $user_approve);
	foreach ($a["app"] as $k => $v) {
		if ($user_name === $v) { $user_status["APPROVE"] = 1; break; }
	};
	if ($user_add !== "registered") {
		$a["add"]= explode ("||",  $user_add);
		foreach ($a["add"] as $k => $v) {
			if ($user_name === $v) { $user_status["ADD"] = 1; } }
		}
	elseif ($user_name !== 'USERNAME') { $user_status["ADD"] = 1; };
	if ($user_see === "registered") {
		if ($user_name !== 'USERNAME') { $user_status["SEE"] = 1; }
		else $user_status["SEE"] = 0;
	}
	elseif ($user_see !== "all") {
		$a["see"]= explode ("||",  $user_see);
		foreach ($a["see"] as $k => $v) {
			if ($user_name !== $v) { $user_status["SEE"] = 0; }
			else { $user_status["SEE"] = 1; break; }
		};
    }	
return $user_status;
}		

switch ($CMS_game){

		case "Castlevania": 
			 $CMS_pref= "castlevania"; 
			 $gamename = "Castlevania";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Civilization5": 
			 $CMS_pref= "civ5"; 
			 $gamename = "Civilization V";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 3;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);			 
			 break;
		case "Disciples3": 
			 $CMS_pref= "disc3"; 
			 $gamename = "Disciples 3";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 100;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Gothic3": 
			 $CMS_pref= "gothic"; 
			 $gamename = "Gothic 3";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins."||Zlo", "registered", "registered", $user_name);
			 break;
		case "GTA4": 
			 $CMS_pref= "gta4"; 
			 $gamename = "GTA 4";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "HP3": 
			 $CMS_pref= "hpotter3"; 
			 $gamename = "Harry Potter 3";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 3;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;		
		case "Oblivion": 
			 $CMS_pref= "oblivion"; 
			 $gamename = "Oblivion";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 80;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;		
		case "SecretsOfPast":
			 $CMS_pref= "secretspast"; 
			 $gamename = "Secrets of Past";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Uncharted": 
			 $CMS_pref= "unc3"; 
			 $gamename = "Uncharted 3";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Worms": 
			 $CMS_pref= "wwp"; 
			 $gamename = "Worms";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 6;
			 $filesOnPage= 150;
			 $filelist_tables=4;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "SHAwakened": 
			 $CMS_pref= "shawakened"; 
			 $gamename = "Sherlock Holmes: The Awakened";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "SHvsJtR": 
			 $CMS_pref= "shvsjtr"; 
			 $gamename = "Sherlock Holmes vs Jack the Ripper";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Diablo2": 
			 $CMS_pref= "diablo2"; 
			 $gamename = "Diablo II";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "GrimTales": 
			 $CMS_pref= "grimtales"; 
			 $gamename = "Grim Tales - The Bride";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 7;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "SecretFiles2":
			 $CMS_pref= "secretfiles2"; 
			 $gamename = "Secret Files 2 - Puritas Cordis";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 100;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Conan": 
			 $CMS_pref= "conan"; 
			 $gamename = "Conan";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 3;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "RE5": 
			 $CMS_pref= "re5"; 
			 $gamename = "Resident Evil 5";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "SH4": 
			 $CMS_pref= "sh4"; 
			 $gamename = "Silent Hill 4";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 3;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "MoveHeroes": 
			 $CMS_pref= "moveheroes"; 
			 $gamename = "PlayStation Move Heroes";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 3;
			 $filesOnPage= 50;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "AoM": 
			 $CMS_pref= "aom"; 
			 $gamename = "Age Of Mythology: The Titans";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 6;
			 $filesOnPage= 120;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "SAW": 
			 $CMS_pref= "saw"; 
			 $gamename = "SAW";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 6;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "RomeTW": 
			 $CMS_pref= "rome"; 
			 $gamename = "Rome: Total War";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 100;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins."||moga", "registered", "registered", $user_name);
			 break;
		case "Batman": 
			 $CMS_pref= "batman"; 
			 $gamename = "BATMAN: Arkham Asylum";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 100;
			 $filelist_tables=1;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "BornIntoDarkness": 
			 $CMS_pref= "bid"; 
			 $gamename = "Born Into Darkness";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins."||mitaka18", "registered", "registered", $user_name);
			 break;
		case "CW": 
			 $CMS_pref= "cw"; 
			 $gamename = "Christmas Wonderland";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "MAL": 
			 $CMS_pref= "mal"; 
			 $gamename = "Mystery of the Ancients Lockwood Manor";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins."||mitaka18", "registered", "registered", $user_name);
			 break;
		case "SC3": 
			 $CMS_pref= "sc3"; 
			 $gamename = "Strange Cases 3: The Secrets of Grey Mist Lake";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins."||mitaka18", "registered", "registered", $user_name);
			 break;
		case "FarCry": 
			 $CMS_pref= "farcry"; 
			 $gamename = "Far Cry";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "MedalOfHonor":
			 $CMS_pref= "moh"; 
			 $gamename = "Medal Of Honor";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "IGI": 
			 $CMS_pref= "igi"; 
			 $gamename = "IGI";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "AlanWake": 
			 $CMS_pref= "alanwake"; 
			 $gamename = "Alan Wake";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 5;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "MaxPayne2": 
			 $CMS_pref= "maxpayne2"; 
			 $gamename = "Max Payne 2";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins."||Fr33style", "registered", "registered", $user_name);
			 break;
		case "KnightsAndMerchants":
			 $CMS_pref= "knm"; 
			 $gamename = "Knights and Merchants";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "AliceMadnessReturns": 
			 $CMS_pref= "alice2"; 
			 $gamename = "Alice: Madness Returns";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "HW2": 
			 $CMS_pref= "hw2"; 
			 $gamename = "Homeworld 2";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "MonkeyIslandSE":
			 $CMS_pref= "mi"; 
			 $gamename = "Monkey Island: Special Edition";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Voyage": 
			 $CMS_pref= "voyage"; 
			 $gamename = "Journey to the Moon";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "DarkestOfDays": 
			 $CMS_pref= "dod"; 
			 $gamename = "Darkest of Days";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Shenmue": 
			 $CMS_pref= "shenmue"; 
			 $gamename = "Shenmue";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "TomClancy": 
			 $CMS_pref= "tomclancy"; 
			 $gamename = "Tom Clancy";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "PrisonBreak": 
			 $CMS_pref= "prisonbreak"; 
			 $gamename = "Prison Break";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk("Phoenix||3pacalypse Now", "registered", "registered", $user_name);
			 break;
		case "AssCreed2": 
			 $CMS_pref= "ac2"; 
			 $gamename = "Assassin\'s Creed II";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Cashflow": 
			 $CMS_pref= "cashflow"; 
			 $gamename = "Cashflow";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "AlanWakeAN": 
			 $CMS_pref= "alanwake_an"; 
			 $gamename = "Alan Wake American Nightmare";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "Torchlight": 
			 $CMS_pref= "torchlight"; 
			 $gamename = "Torchlight";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
		case "TheWalkingDead1": 
			 $CMS_pref= "walkingdead1"; 
			 $gamename = "The Walking Dead 1";	//Game's title for stylish purposes
			 $page_rows = 25; //Number of rows to be displayed on 1 viewtext page
			 $filerows = 4;
			 $filesOnPage= 50;
			 $filelist_tables=2;
			 $user_rights = privilege_chk($admins, "registered", "registered", $user_name);
			 break;
}
			 $text_table = $CMS_pref."_text"; //Game's table with the text
			 $text_table = mysql_real_escape_string($text_table);
			 $translations_table = $CMS_pref."_translations"; //Game's table with the users translations
			 
//----------------------------------------------------------
//----------- UNCHANGEABLE PART ----------------------------
//----------------------------------------------------------
function sortMultyArray($array, $index, $order='asc', $natsort=FALSE, $case_sensitive=FALSE) 
{
	if(is_array($array) && count($array)>0) 
	{
	   foreach(array_keys($array) as $key) 
		   $temp[$key]=$array[$key][$index];
		   if(!$natsort) 
			   ($order=='asc')? asort($temp) : arsort($temp);
		  else 
		  {
			 ($case_sensitive)? natsort($temp) : natcasesort($temp);
			 if($order!='asc') 
				 $temp=array_reverse($temp,TRUE);
	   }
	   foreach(array_keys($temp) as $key) 
		   (is_numeric($key))? $sorted[]=$array[$key] : $sorted[$key]=$array[$key];
	   return $sorted;
  }
  return $array;
}  

function punctuation_check($test) {
	$test = str_replace("\r\n", " ", $test);
	$test = preg_replace('/[[:space:]]+/', ' ', $test);
	$test = preg_replace('/( )([\.,!\?])/', '$2', $test);
	$test = preg_replace('/([А-я\.,!\?])([\.,!\?])([А-я])/', '$1$2 $3', $test);
    return trim($test);
}
// ============================================================ //
/* =======================>> CMS <<============================ */
// ============================================================ //
function CMS_statistic1SAVE($count) {
	global $user_name, $CMS_game;
	if (isset($count)) {
		mysql_query("INSERT INTO cms_statisticONE (username, game, strings, date) VALUES ('$user_name', '".mysql_real_escape_string($CMS_game)."', '$count', CURDATE()) ON DUPLICATE KEY UPDATE strings=strings+$count");
	}
}
function CMS_statistic2SAVE($files,$strings,$transes,$percent) {
	global $CMS_game;
	if (isset($files)) {
		mysql_query("INSERT INTO cms_statisticTWO (game, files, strings, translated, percent) VALUES ('".mysql_real_escape_string($CMS_game)."', '$files', '$strings', '$transes', '$percent') ON DUPLICATE KEY UPDATE translated='$transes', percent='$percent'");
	}
}

function CMS_dictionaryLoad() {
	global $CMS_game;
	$rowss= mysql_query("SELECT * FROM cms_dict WHERE `game` = '".mysql_real_escape_string($CMS_game)."'"); $a=0;
	while ($row = mysql_fetch_array($rowss)) {
		if ($row['status']==1) {
			$words[$a]['word']= $row['keyword'];
			$words[$a]['translation']= $row['translation'];
			$words[$a]['game']= $row['game'];
			$a++;
		}
	}
	return $words;
}		

function CMS_dictionarySave() {
	global $user_name, $CMS_game;
		$word= mysql_real_escape_string(trim(str_replace("\r\n","",$_POST['dict_word']))); $trans= mysql_real_escape_string($_POST['dict_trans']); $date= date("Y-m-d");
		$trans= "=> <b>$trans</b><br>$user_name ($date)";
	if (isset($_POST['dicsubmit']) and $_POST['dict_trans']!='') {
		mysql_query("INSERT INTO cms_dict (game, keyword, translation) VALUES ('".mysql_real_escape_string($CMS_game)."', '$word', '$trans') ON DUPLICATE KEY UPDATE translation = CONCAT(translation, '<BR>$trans'), status = 0");
	}
}

function CMS_dictionaryEcho() {
	global $user_rights;
	if ($user_rights['ADD']===1) {
		echo <<<HTML
				<br><center>	
				<form action="" method="post" style="display: inline;">
				<b class="textWHITE unselectable">Дума: </b><textarea name="dict_word" class="expand17-28 tbox" cols=60 style='vertical-align:middle;'></textarea><br>
				<b class="textWHITE unselectable">Превод: </b><textarea name="dict_trans" class="expand17-100 tbox" cols=58 style='vertical-align:middle;'></textarea><br>
				<input name="dicsubmit" type="submit" value="Изпрати" class="button"></center>
				<div class='forumheader textGREY'>N.B. Тук може да подавате английските термини и техните преводи, след което те ще бъдат маркирани навсякъде в английския текст. Молим да използвате тази опция, за да се уеднаквят използваните имена, места, понятия, предмети и т.н.</div>
HTML;
	}
}

function CMS_insertDictTooltips($dictionary, $strings) { $a=0;
	foreach ($strings as $string) {
		$arr[$a]= $string;
		foreach ($dictionary as $word) {
			$keyword= trim($word['word']); $tooltip= $word['translation'];
			$arr[$a] = preg_replace('@(' . preg_quote($keyword, '@') . ')@i', "<span class='tooltip'>\\1<span class='classic unselectable'>$tooltip</span></span>", $arr[$a]);
		}
		$a++;
	}
	unset($strings);
	return $arr;
}

function CMS_gamePagerInitiate() {
	global $CMS_game, $CMS_file, $page_rows, $text_table;
	$search= "$CMS_game??$CMS_file";
	$temp = mysql_query("SELECT * FROM cms_gamesmain WHERE `game` = '".mysql_real_escape_string($search)."'");
	if (mysql_num_rows($temp)==0) {
		$newgame = mysql_query("SELECT content FROM $text_table WHERE file_name = '".mysql_real_escape_string($CMS_file)."' and content <> ''");
		$rows_count = 0;
		while($nextrow = mysql_fetch_array($newgame)){
			$rows_count++;
		}
		$pages_count = ceil($rows_count/$page_rows); //Number of all pages
		mysql_query("INSERT INTO cms_gamesmain (game, pages) VALUES ('".mysql_real_escape_string($search)."', '$pages_count')");
	}
	else { 
		$temp = mysql_fetch_array($temp);
		$pages_count = $temp['pages'];
	}
	return $pages_count;
}

function CMS_gamePagerOverall_Load() {
	global $CMS_game, $CMS_file;
	$search= "$CMS_game??$CMS_file??";
	$rowss= mysql_query("SELECT * FROM cms_overalpages WHERE `page` LIKE '".mysql_real_escape_string($search)."%'");
	while ($row= mysql_fetch_array($rowss)) {
		$key= str_replace ($search, "", $row['page']);
		$result[$key]= $row['status'];
	}
	return $result;
}

function CMS_gamePagerOverall_Save($content, $text_id) {
	global $CMS_game, $CMS_file, $CMS_page;
	$insert= "$CMS_game??$CMS_file??$CMS_page"; $all= 0; $cyr= 0;
	foreach ($content as $key => $row) {
		$all++;
		if(preg_match("/[а-яА-Я]{2,}/u", $row) OR preg_match("/(_IGcoLLen){1}/", $text_id[$key])){
			$cyr++;
		}
	}
	if ($all/$cyr===1) { $status= "green"; }
	elseif ($all/$cyr>0) { $status= "yellow"; }
	else { $status= "red"; }
	mysql_query("INSERT INTO cms_overalpages (page, status) VALUES ('".mysql_real_escape_string($insert)."', '$status') ON DUPLICATE KEY UPDATE status='$status'");
}

function CMS_activitySave($location) {
	global $user_name, $user_id, $CMS_game, $CMS_file, $CMS_page;
	if ($user_name != 'USERNAME') {
		$user_history= mysql_query("SELECT * FROM cms_actusers WHERE user_name = '$user_name'"); //Loading present history
		if (mysql_num_rows($user_history)!=0) {
			$user_history= mysql_fetch_array($user_history);
			$temp= explode("\n", $user_history['location_history']);
			foreach ($temp as $value) {
				$location_history[]= explode("~~", $value); 
			}
			unset($temp); $temp='';
			foreach ($location_history as $key => $value) {
				if(isset($value[0]) AND isset($value[1])) {$temp.=$value[0]."~~".$value[1]."\n";}
				if ($key>99) break;
			}
		}
		else {$temp='';}

		$temp2= $location;
		if (isset($CMS_game)) { $temp2.="?game=$CMS_game"; }
		if (isset($CMS_file)) { $temp2.="&name=$CMS_file"; }
		if (isset($CMS_page)) { $temp2.="&page=$CMS_page"; }
		$temp = $temp2."~~".time()."\n".$temp;
		
		$temp= mysql_real_escape_string($temp);
		$temp2= mysql_real_escape_string($temp2);
		
		mysql_query("INSERT INTO cms_actusers (user_id, user_name, location_history, location_present) VALUES ('$user_id', '$user_name', '$temp', '$temp2') ON DUPLICATE KEY UPDATE location_history='$temp', location_present='$temp2'");
	}
	//------------------------------------------
	$doadd='';
	if (isset($CMS_game)) { 
		if ($doadd!='') { $doadd.='&'; }
		$doadd.="game=$CMS_game";
	}
	if (isset($CMS_file)) {
		if ($doadd!='') { $doadd.='&'; }
		$doadd.="file=$CMS_file";
	}
	if (isset($CMS_page)) { 
		if ($doadd!='') { $doadd.='&'; }
		$doadd.="page=$CMS_page";
	}
	if ($doadd!='') { $doadd="?$doadd"; }
	
	mysql_query("INSERT INTO cms_ipact (ip,username,visited) VALUES ('".USERIP."','".USERNAME."','$location$doadd')");
}

function CMS_activityLoad() { $a=0;
	$user_history= mysql_query("SELECT * FROM cms_actusers");
	while ($row= mysql_fetch_array($user_history)) {
		$tempo= explode("\n", $row['location_history']);
		foreach ($tempo as $value) {
			if($value!='') {
				$exploded= explode("~~", $value);
				$result[$a]['date']= $exploded[1]; 
				$result[$a]['user_name']= $row['user_name'];
				$result[$a]['user_id']= $row['user_id'];
				$result[$a]['href']= $exploded[0];
				$a++;
			}
		}
	}
	$result= sortMultyArray($result, 'date', 'desc');
	return $result;
}

function CMS_lastApprovedSave($approved_rows, $touser) {
	$unseen= mysql_query("SELECT approved_unseen FROM cms_actusers WHERE user_name='$touser'");
	while ($user= mysql_fetch_array($unseen)) {
		$result= $user['approved_unseen']+$approved_rows;
	}
	mysql_query("UPDATE cms_actusers SET `approved_unseen`='$result' WHERE user_name='$touser'");
}

function CMS_lastApprovedLoad() {
	global $user_name;
	$lastApproved= mysql_query ("SELECT approved_rows, approved_unseen FROM cms_actusers WHERE user_name = '$user_name'");
	while ($user= mysql_fetch_array($lastApproved)) {
		$result['rows']= $user['approved_rows']+$user['approved_unseen'];
		$result['unseen']= $user['approved_unseen'];
	}
	$temp= $result['rows'];
	mysql_query("UPDATE cms_actusers SET `approved_rows`='$temp', `approved_unseen`='0' WHERE user_name = '$user_name'");
	return $result;
}

function CMS_lastApprovedEcho() {
	global $user_name;
	$temp= CMS_lastApprovedLoad();
		$rowss= $temp['rows'];
		$unseen= $temp['unseen'];
	if ($unseen != '0' AND $user_name != "USERNAME") {
		echo "<br><center><div class= 'cmsMessage'><b>От последната ви визита насам бяха одобрени ваши реплики на брой: $unseen!<br>С което вашите одобрени реплики станаха: $rowss</b></div></center>";
	}
}

function CMS_pageEdittedSave() {
	global $user_name, $CMS_game, $CMS_file, $CMS_page;
	$page= "$CMS_game??$CMS_file??$CMS_page"; $page= mysql_real_escape_string($page);
	$user= "$user_name-->||~~";
	$get= mysql_query ("SELECT * FROM cms_editpages WHERE `page` = '$page'");
	if (mysql_num_rows($get)!=0) {
		$referee= str_replace($user, '', $get['referee']);
		$referee.= $user;
		mysql_query("UPDATE cms_editpages SET `referee` = '$referee', `status` = '1' WHERE `page` = '$page'"); }
	else {
		$referee= $user;
		mysql_query("INSERT INTO cms_editpages (page, referee, status) VALUES ('$page', '$referee', '1')"); 
	}
}

function CMS_pageEdittedLoad() {
	global $CMS_game, $CMS_file, $CMS_page;
	$page= "$CMS_game??$CMS_file??$CMS_page"; $page= mysql_real_escape_string($page);
	$get= mysql_query ("SELECT * FROM cms_editpages WHERE `page` = '$page'");
	$get= mysql_fetch_array ($get);
	if ($get['status']==1) {
		$referees= explode("-->||~~", $get['referee']);
		$referees= clear_array($referees); }
	else { 
		$referees=FALSE;
	}
	return $referees;
}

function CMS_pageEdittedEcho() {
	$get= CMS_pageEdittedLoad();
	$temp= ''; $boolean= FALSE;
	if ($get!=FALSE) {
		foreach ($get as $value) {
			$temp.= "<span class='textWHITE'><b>$value</b></span>, "; }
		echo "<br><center><div style= 'color:black; border: 1px solid #FFF; border-radius: 1px; border-color: green; background:grey;'>Тази страница е била отбелязана като проверена от: $temp<br>Натиснете <a href=\"javascript:toggle('hiddenform');\">тук</a>, за да разгледате съдържанието на страницата.</div></center>";
		$boolean= TRUE;
	}
return $boolean;
}

function CMS_pendingTranslationsLoad($what="all") {
	global $translations_table, $CMS_file; $result= array(); $num=0;
	if ($what==="all") {
		$arr_pending = mysql_query("SELECT * FROM $translations_table WHERE status like 'В процес на проверка...%' ORDER BY time DESC"); }
	elseif ($what==="for file") {
		$arr_pending = mysql_query("SELECT id, page FROM $translations_table WHERE status like 'В процес на проверка...%' AND file_name = '$CMS_file' ORDER BY page ASC, id ASC"); }
	elseif ($what==="for game") {
		$arr_pending = mysql_query("SELECT id, page, file_name FROM $translations_table WHERE status like 'В процес на проверка...%' ORDER BY file_name ASC, page ASC, id ASC"); }
	while ($entity= mysql_fetch_array($arr_pending)) {
		if (isset($entity['id'])) { $result[$num]['id']= $entity['id']; }
		if (isset($entity['page'])) { $result[$num]['page']= $entity['page']; }
		if (isset($entity['file_name'])) { $result[$num]['file_name']= $entity['file_name']; }
		if (isset($entity['translation'])) { $result[$num]['translation']= $entity['translation']; }
		if (isset($entity['status'])) { $result[$num]['status']= $entity['status']; }
		if (isset($result[$num]['translator_name'])) { $result[$num]['translator_name']= $entity['translator_name']; }
		if (isset($result[$num]['time'])) { $result[$num]['time']= $entity['time']; }
		$num++;
	}
	$result['count']= mysql_num_rows($arr_pending);
	return $result;
}
	
//-----------------------------------------------------
//-----------------------------------------------------

function CleanText($value){
	return mysql_real_escape_string(htmlentities(stripslashes($value))); //Strips the code of anything that a hacker might try to do ;) Think smart!
}

function redirect_to($path){
	return header("location: $path");	
}

function get_id(){
	if(!isset($_GET['id'])){
		$id = 1;	
	}
	else{
		$id = (int)$_GET['id'];	
	}
	return $id;	
}

function get_page(){
	if(!isset($_GET['page'])){
		$CMS_page = 1;	
	}
	else{
		$CMS_page = (int)$_GET['page'];	
	}
	return $CMS_page;
}

function clear_array(&$array){
	foreach($array as $k => $v){
		$v = (string)$v;
		$v = trim($v);
		if(empty($v) or $v == '' or !isset($v)){
			unset($array[$k]);
		}
	}
	return $array;
}

function is_empty($value){
	$value = (string)$value;
	$value = trim($value);
	if(empty($value) or $value == '' or !isset($value)){
		return true;	
	}
	else{
		return false;	
	}
}

function str2minute(&$value){
	if($value == "00"){
		$value = 0;
	}
	elseif(substr($value, 0, 1) == "0"){
		$value = (int)substr($value, 1, 1);
	}
	else{
		$value = (int)$value;
	}
	return $value;
}

function ramka($act) {
	if ($act=='open') {
		echo "<div class='custmarg'><div class='mtopl'><div class='mtopr'><div class='mtop'></div></div></div><div class='ml'><div class='mr'><div class='mtext2' style='width:98.5%!important; margin-left:6px!important;'>";
	}
	if ($act=='close') {
		echo "</div><div style='min-height:1px;'></div></div></div><div class='mbotl'><div class='mbotr'><div class='mbot'></div></div></div></div>";
	}
}

function months_inBG($string) {
	$eng= array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	$bg= array("януари", "февруари", "март", "април", "май", "юни", "юли", "август", "септември", "октомври", "ноември", "декември");
	$string= str_replace($eng, $bg, $string);
	return $string;
};

function autosysmessage1($counted) {
	global $gamename; $idiot=USERNAME; $idiot[0]=strtoupper($idiot[0]);

	$is_1= array("Нищо, първият път винаги е трудно.",
				 "Хайде още 1 за мама!",
				 "Добре, че играта е къса.",
				 "Какво ми говориш! И аз само от нули и единици разбирам!",
				 "$idiot си заслужи бисквитка",
				 "Ха, още една! А не, това беше за бирата...",
				 "$idiot, ако това беше последната реплика от играта, ти пращам една бира веднагически!",
				 "Не размерът е важен...",
				 "А снощи един пич прати 2. Знам, че го желаеш...");
    $ist_4=array("Поредното доказателство, че с мерак всичко се постига!");	
	$is_5= array("5x5=25... Малко системен хумор.",
				 "Gimme five!",
				 "$idiot, свий пет пръстта и следващия път давай направо с шепа!",
				 "Ако повярваш... ще станат 10! Шегичка... Не признавам кодове!");
	$ist_9= array();
	$is_10= array();
	$ist_14=array();
	$is_15= array();
	$ist_19=array();
	$is_20= array();
	$ist_24=array();
	$is_25= array("$idiot ми изкърти системните чакри.",
				  "$idiot, ожени се за мен. Ще си имаме хубави преводни модулчета!",
				  "$idiot заема специално място в електрическото ми сърце!",
				  "$idiot is the last of his kind",
				  "$idiot, потърси ме в скритите страници!",
				  "$idiot, понякога си мечтая за теб!",
				  "$idiot знае как да изпълни една скромна системка.");
	$is_all=array("$idiot is the best!",
				  "Една малка крачка за $idiot, но гигантска крачка за PlayON.",
				  "All hail $idiot",
				  "Остават още... Кой ти брои!",
				  "Така се прави, мой човек!",
				  "$idiot е моят герой!",
				  "$idiot знае какво прави!",
				  "PlayON му благодари!",
				  "$idiot, ти ме изпълваш!",
				  "Ама, и аз съм една проститутка - всички ми вкарват!",
				  "$idiot, никога няма да бъда същата!",
				  "Преядох...",
				  "Виждам реплики...",
				  "Боже, наистина се надявам, че са ме програмирали жена.",
				  "Просто нямам думи!",
				  "I see green words...",
				  "$idiot, виждаш това, защото ме няма. Ако бях тук, нямаше да видиш нищо.",
				  "$idiot, в момента и други ме опипват. Но ти си най-добрият.",
				  "$idiot, текстът ти отиде направо в кошчето… Базик, първо да изчакаме координатора.",
				  "Благодарим ви, $idiot. Кредитната ви карта беше таксувана 2 лева за първите 10 думи и по 10 стотинки за всяка следваща.",
				  "Благодарим за съдействието ви. Вашият превод беше въведен на 356 място в списъка на чакащите и ще бъде проверен до 19 седмици.",
				  "Преводът ви не струва. Моля, пъхнете ръката си във флопито за наказателен електрошок.",
				  "$idiot, прочитайки написаното от теб, реших да напусна този сървър и да отида в истински цирк.",
				  "$idiot, ти от кой език на кой превеждаш?",
				  "$idiot, това отиде в грешното отверстие. Но ми хареса!",
				  "$idiot, ти сваляш ли ме? Или някой идиот ми е качил порно игра без да ме предупреди?",
				  "$idiot, имам дълбоки подозрения, че ти си високотехнологичен вирус, пратен да намери пътя си до сърцето ми.",
				  "$idiot, намери си реплика -I love you- и ми прати превода.",
				  "$idiot, ще го запомня!",
				  "$idiot, вечно ще помня думите ти!",
				  "INTERNAL ERROR: Too many games wanting your translation. Please, serve them all.",
				  "$idiot, ако четеш това съобщение, значи си събрал смелост да пратиш превода си. PlayON те поздравява! Да му мислят проверяващите.",
				  "Един координатор умря, редактирайки преведения текст.",
				  "В бой с преведения текст загинаха един редактор и двама администратори.",
				  "След стореното от $idiot, програмистите ми написаха команда за саморазрушение.",
				  "Редакторът на $gamename получи оргазъм.",
				  "БАН сложи бан на $idiot за дълбоко погазване на научните догми. В отговор, администрацията на PlayON сложи бан на БАН.",
				  "Когато $idiot преведе реплика в $gamename, ще види ли някой, че превел е $idiot реплика в $gamename?",
				  "Понякога скритите игри си мечтаят за докосването на $idiot.",
				  "$idiot, крещя името ти! Жалко, че не го знам…",
				  "Днес е денят и ще се случва отново, и отново…",
				  "$idiot, $gamename не те заслужава. Ако си търсиш истинска играчка, потърси ме в скритите страници…",
				  "$gamename, ако го пожелаеш истински, $idiot ще се върне…",
				  "$idiot, понякога ми се иска да те клонирам… Но после си спомням, че не са останали много редактори за умиране.",
				  "Давайте кофата, че мястото свърши.");
				  
	if ($counted==1) { $plsing='реплика'; } else $plsing="реплики";
				  
	switch($counted) {
		case 1:  $sysecho=array_merge($is_all,$is_1);break;
		case 2:
		case 3:
		case 4:  $sysecho=array_merge($is_all,$ist_4);break;
		case 5:  $sysecho=array_merge($is_all,$ist_4,$is_5);break;
		case 6:
		case 7:
		case 8:
		case 9:  $sysecho=array_merge($is_all,$ist_9);break;
		case 10: $sysecho=array_merge($is_all,$ist_9,$is_10);break;
		case 11: 
		case 12:
		case 13:
		case 14: $sysecho=array_merge($is_all,$ist_14);break;
		case 15: $sysecho=array_merge($is_all,$ist_14,$is_15);break;
		case 16:
		case 17:
		case 18:
		case 19: $sysecho=array_merge($is_all,$ist_19);break;
		case 20: $sysecho=array_merge($is_all,$ist_19,$is_20);break;
		case 21:
		case 22:
		case 23:
		case 24: $sysecho=array_merge($is_all,$ist_24);break;
		case 25: $sysecho=array_merge($is_all,$ist_24,$is_25);break;
	}
	$sysechoed= $sysecho[array_rand($sysecho)];
		
	$texted= mysql_real_escape_string("<span class='autosys1'>$idiot</span> преведе <span class='autosys2'>$counted</span> $plsing от <span class='autosys3'>$gamename</span>.<br><span class='autosys4'></span><span class='autosys5'>$sysechoed</span>");
	
	mysql_query("INSERT INTO cms_automessage1(message) VALUES('$texted')");
}
function autosysmessage2($counted,$translator,$unID,$unGAME) {
	global $gamename; global $CMS_page; global $CMS_file; $idiot=USERNAME; 
	if ($counted==1) { $plsing='реплика'; } else $plsing="реплики";
		$get= mysql_query("SELECT level_access FROM `admin_panel` WHERE `game_name` = '$gamename'");
		$get = mysql_fetch_array($get);
		if ($get['level_access']==0) {
			$addtext= "За сверка, <a href='http://playonbg.info/translations/cms/viewtext.php?game=$unGAME&name=$CMS_file&page=$CMS_page&go=pending#$unID'>тук</a>. ";
		} else $addtext="";
	$texted= mysql_real_escape_string("<span class='autosys1'>PlayOn координатор ($idiot)</span> <span class='autosys8'>одобри</span> <span class='autosys2'>$counted</span> $plsing на <span class='autosys1'>$translator</span> в играта <span class='autosys3'>$gamename</span>.<br><span class='autosys4'></span>$addtext<span class='autosys5'>PlayOnBG благодари на преводача!</span>");
	mysql_query("INSERT INTO cms_automessage1(message) VALUES('$texted')");
}
function autosysmessage3($counted,$translator,$unID,$unGAME){
	global $gamename; global $CMS_page; global $CMS_file; $idiot=USERNAME;
	$idiot=USERNAME; $idiot[0]=strtoupper($idiot[0]);
	if ($counted==1) { $plsing='реплика'; } else $plsing="реплики";
		$get= mysql_query("SELECT level_access FROM `admin_panel` WHERE `game_name` = '$gamename'");
		$get = mysql_fetch_array($get);
		if ($get['level_access']==0) {
			$addtext= "За улеснение на координатора, <a href='http://playonbg.info/translations/cms/viewtext.php?game=$unGAME&name=$CMS_file&page=$CMS_page&go=pending#$unID'>тук</a>. ";
		} else $addtext="";
	$texted= mysql_real_escape_string("<span class='autosys1'>$idiot</span> провери и редактира <span class='autosys2'>$counted</span> $plsing на <span class='autosys1'>$translator</span> в играта <span class='autosys3'>$gamename</span>.<br><span class='autosys4'></span><span class='autosys6'>Репликите ще бъдат одобрени след окончателна проверка от страна на координатора на играта!</span> $addtext");
	mysql_query("INSERT INTO cms_automessage1(message) VALUES('$texted')");
}	
	
function autosysmessage4($translator,$unID,$unGAME){
	global $gamename; global $CMS_page; global $CMS_file; $idiot=USERNAME;
	if ($get['level_access']==0) {
			$addtext= "За справка, <a href='http://playonbg.info/translations/cms/viewtext.php?game=$unGAME&name=$CMS_file&page=$CMS_page&go=pending#$unID'>тук</a>. ";
		} else $addtext="";
	$texted= mysql_real_escape_string("<span class='autosys1'>Playon координатор ($idiot)</span> <span class='autosys7'>отхвърли</span> превод на <span class='autosys1'>$translator</span> в играта <span class='autosys3'>$gamename</span>.<br><span class='autosys4'></span><span class='autosys6'>Припомняме, че нередактиран Google Translate не се толерира и се извиняваме, ако е станала грешка!</span> $addtext");
	mysql_query("INSERT INTO cms_automessage1(message) VALUES('$texted')");
}

function autosysmessage5($unGAME){
	global $gamename; $idiot=USERNAME;
	$texted= mysql_real_escape_string("<span class='autosys1'>Playon координатор ($idiot)</span> <span class='autosys7'>изтри</span> превод в играта <span class='autosys3'>$gamename</span>.");
	mysql_query("INSERT INTO cms_automessage1(message) VALUES('$texted')");
}

function str_getBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
		if($end!='') {
			$r = explode($end, $r[1]);
			return $r[0];
		}
		else return $r[1];
    }
    return '';
}
?>